Ext.onReady(function(){
    Ext.state.Manager.setProvider(
        new Ext.state.SessionProvider({
            state: Ext.appState
        }));

    var button = Ext.get('demention');

    button.on('click', function(){
        Ext.QuickTips.init();
        var xg = Ext.grid;  
        var sender={};
        var re = Ext.ComponentMgr.get("ggg").getSelectionModel().getSelected();

        if (re == null || re == "") {
            Ext.Msg.alert('提示', '请选择需要关联的指标！');
            return ;
        } else{
        var isvalid=re.data.isvalid;
        if(isvalid==0){
            Ext.Msg.alert('提示', '该指标不可用!');
            return ;
        }
            var repid = re.data.repid;
            var openUrl = basePath
            + 'JarpListener?className=cn.com.jsepc.rep.demension.DementionDAO';
            openUrl += '&methodName=getSelect_Grid&paramCount=1&param_0='+repid;   
    
            var jReader1 = new Ext.data.JsonReader({
                fields : [{
                    name : 'demid'
                },{
                    name : 'repid'
                },{
                    name : 'demname'
                },{
                    name:'availsname'
                },{
                    name:'dimtype'
                },{
                    name:'dimorder'
                },{
                    name:'isselect'
                }]
            });
	
            var store = new Ext.data.Store({
                autoLoad:true,
                url:openUrl,
                reader : jReader1
            });

            store.setDefaultSort('dimorder', 'ASC');
            var sm = new xg.CheckboxSelectionModel({
                checkOnly:true,
                listeners: {
     
                    selectionchange: function(sm) {

                    }
                }
            });
	
            var cm = new xg.ColumnModel( [
                sm,							
                {
              
                    id : 'demid',
                    name       :'demid',
                    header   : '维度编号',
                    sortable : true, 
                    dataIndex: 'demid', 
                    hidden:true
                
                },{
                
                    id : 'repid',
                    name       :'repid',
                    header   : '指标编号', 
                    width:140,
                    sortable : true, 
                    dataIndex: 'repid',
                    hidden:true
                },
                {
                    name       :'demname',
                    header   : '维度名称', 
                    width:140,
                    sortable : true, 
                    dataIndex: 'demname'
                },{
                    name:"availsname",
                    header:"别名",
                    width:140,
                    sortable:true,
                    dataIndex:'availsname',
                    editor: new Ext.form.Field({
                        allowBlank: true,
                        decimalPrecision : 0,
                        allowNegative: false
                    })
                },{
                    name:"dimtype",
                    header:"维度类型",
                    width:140,
                    sortable:true,
                    dataIndex:'dimtype',
                    hidden:true
                },{
                    name:"dimtypename",
                    header:"维度类型",
                    width:140,
                    sortable:true,
                    dataIndex:'dimtype',
                    //hidden:true,
                    renderer : function(v) {
                        if (v == 1) {
                            return "单位";
                        } else if (v == 2) {
                            return "时间";
                        }else{
                            return "其他";
                        }
                    }
                },{
                    name:'dimorder',
                    header:'排序',
                    width:140,
                    sortable:true,
                    dataIndex:'dimorder',
                    editor: new Ext.form.Field({
                        allowBlank: true,
                      //  decimalPrecision : 0,
                        allowNegative: false
                    }),
                    renderer : function(v) {
                        if (v == 0) {
                            return "";
                        }else{
                        	return v;
                        }
                    }
                },{
                    header:'排序',
                    hidden:true,
                    dataIndex:'isselect',
                    renderer:function(value,cellmeta,record,rowIndex){
                        if(value!=""&&value!="0"){
                            sm.selectRow(rowIndex,true);
                        }else{
                        //  sm.deselectRow(rowIndex,true);
                        }
                    }
                }
                ]);
	     
            cm.defaultSortable = true;
            sm.on("rowselect",function(s,rowindex,record){
    		
                if(record.get("availsname")==""){
                    record.set("availsname",record.data.demname);
                }
    		
            });
    
    
    
            var relate_demension_grid = new Ext.grid.EditorGridPanel({
                forceFit:true,
                clicksToEdit:1, 
                id : 'demention_grid',
                viewConfig : {
                    forceFit : true
                },
                store:store,
                sm:sm,
                cm:cm,  
                columnLines:true,
                height: 500,
                stateful: true,
                stateId: 'relate_demension_grid',
                region: 'center',
                width: 480,
                enableHdMenu:false,
                frame:true
            }); 
        
        

            var win_rep_demension = new Ext.Window({
                title: '维度信息',
                closable:true,
                width:600,
                height:350,
                border:true,
                plain:true,
                layout: 'border',
                tbar : [ new Ext.Toolbar.TextItem({                
                    }),{
                    text : '确定',
                    handler:function(){
                        //提交已有更改
                        relate_demension_grid.getStore().commitChanges();
                        var rows = relate_demension_grid.getSelectionModel().getSelections(); 
                        if(rows.length==0){
                            Ext.MessageBox.show({
                                title:"提示",
                                msg:'是否要删除该指标所关联的所有维度',
                                buttons:{
                                    "yes":"确定",
                                    "no":"取消"
                                },
                                fn: function(btn){
                                	if(btn=='yes'){
						                delete_demension();
						            }
						            else if(btn=='no'){
						                return ;
						            }
                                },
                                icon: Ext.MessageBox.QUESTION
                            })
                      //      return ;
                            function delete_demension(){
                                var openUrl = basePath
                            + 'JarpListener?className=cn.com.jsepc.rep.demension.DementionDAO';
                            openUrl += '&methodName=updata_rep_Demension&paramCount=1&param_0='+repid;
                            httpR_itemInfo=null;
                            httpR_itemInfo = getXMLHttpRequest();
                            httpR_itemInfo.onreadystatechange = returnItemSave_null;
                            httpR_itemInfo.open("POST", openUrl, true);
                            httpR_itemInfo.send(Ext.util.JSON.encode(sender));
                            function returnItemSave_null() {
                                if (httpR_itemInfo.readyState == 4) {
                                    if (httpR_itemInfo.status == 200) {
                                        ret = httpR_itemInfo.responseText;
                                        if (ret == 'ok') {
                                            Ext.MessageBox.alert( "提示",'指标关的联维度删除成功！');
                                            win_rep_demension.close(this);
                                            Ext.ComponentMgr.get("ggg").store.reload();
                                        } else if(ret=="wrong") {
                                            Ext.MessageBox.alert(  "提示",'指标关联维度更新失败！');
                                        }
                                        else{
                                            Ext.MessageBox.alert(  "提示",'未知错误');
                                        }
                        
                                    }
                                }
                            }
                            }
                        }
                        else{
                            //判断是否关联了同种类型的维度
                            var danwei_count=0;
                            var shijian_count=0;
                            for(var i=0;i<rows.length;i++){
                                if(rows[i].data.dimtype==1){
                                    danwei_count+=1;
                                }
                                if(rows[i].data.dimtype==2){
                                    shijian_count+=1;
                                }
                            }
                            if(danwei_count>1){
                                Ext.MessageBox.alert("提示","只能关联一种单位维度");
                            
                            }
                        
                            if(shijian_count>1){
                                Ext.MessageBox.alert("提示","只能关联一种时间维度");
                                return ;
                            }
                        
                        
                            var array=[];
                            for(var i=0;i<rows.length;i++){
                                var o={};
                                o.repid=repid;
                                o.demid=rows[i].data.demid;
                                o.availsname=rows[i].data.availsname;
                                if(rows[i].data.factdimCol==""){
                                    Ext.MessageBox.alert("错误","没有设置关联字段")
                                    return;
                                }
                                o.factdimCol=rows[i].data.factdimCol;
                                o.dimorder=rows[i].data.dimorder;
                                array.push(o);
                            }
                            sender.listData=array;
                            Ext.MessageBox.show({
                                title:'提示',
                                msg: '是否确定操作，一旦确定，将覆盖此前关联过的维度及创建的事实表,此前的数据仍然备份在数据库中，如有需要，请联系技术人员',
                                //  buttons: Ext.MessageBox.YESNOCANCEL,
                                buttons:{
                                    'yes':'确定',
                                    'no':'关闭',
                                    'cancle':'取消'
                                },
                                fn: showResult,
                                icon: Ext.MessageBox.QUESTION
                            });
                        }
                    
                    }
               
                },'-',{
                    text : '关闭',
                    handler : function() {
                        win_rep_demension.close();
                    }
                }
                ],
                items: [relate_demension_grid]
            });

            win_rep_demension.show(this);
        
        }
        
        function showResult(btn){
            if(btn=='yes'){
                sava_rep_Demension(repid,sender);
            }
            else if(btn=='no'){
                return ;
            }
        };
        function sava_rep_Demension(repid,objInfo){
            var openUrl = basePath
            + 'JarpListener?className=cn.com.jsepc.rep.demension.DementionDAO';
            openUrl += '&methodName=updata_rep_Demension&paramCount=1&param_0='+repid;
            httpR_itemInfo=null;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = returnItemSave;
            httpR_itemInfo.open("POST", openUrl, true);
            httpR_itemInfo.send(Ext.util.JSON.encode(objInfo));
            function returnItemSave() {
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {
                            Ext.MessageBox.alert( "提示",'指标关联维度更新成功！');
                            create_Fact();
                        } else if(ret=="wrong") {
                            Ext.MessageBox.alert(  "提示",'指标关联维度更新失败！');
                        }
                        else{
                            Ext.MessageBox.alert(  "提示",'未知错误');
                        }
                        
                    }
                }
            }
            
        }
        
        function create_Fact() {
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.Fact_table';
            saveItemInfoUrl += '&methodName=Create_facttable';
            saveItemInfoUrl += '&paramCount=1&param_0='+repid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = returnFact;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send();
        }
                    
        function returnFact() {
            if (httpR_itemInfo.readyState == 4) {
                if (httpR_itemInfo.status == 200) {
                    ret = httpR_itemInfo.responseText;
                    
                    if (ret == 'ok') {
                        Ext.MessageBox.alert('提示', '指标事实表创建成功！');
                       // insert_Fact();
                        win_rep_demension.close(this);
                         Ext.ComponentMgr.get("ggg").store.reload();
                    } else if (ret == 'auto') {
                        //Ext.MessageBox.alert('提示', '因为该事实表是自动生成的');
                        win_rep_demension.close(this);
                    } else{
                        Ext.MessageBox.alert('提示', '指标事实表创建失败！');
                        win_rep_demension.close(this);
                    }
                }
            }
        }
        
        function insert_Fact() {
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.Fact_table';
            saveItemInfoUrl += '&methodName=setRepdata';
            saveItemInfoUrl += '&paramCount=1&param_0='+repid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            //httpR_itemInfo.onreadystatechange = returnFact;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send();
        }
        
        
    });
    
});


